import { FC, useEffect, useRef } from "react";
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js'

import {
    Mesh,
    WebGLRenderer, Scene,
    PerspectiveCamera,
    AxesHelper,
    PointLight,
    Fog,
    AmbientLight,
    MeshPhongMaterial,
    SphereGeometry,
    MeshLambertMaterial,
} from 'three'
import State from 'three/examples/jsm/libs/stats.module.js'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
const page: FC = () => {
    const container = useRef<HTMLDivElement>(null),
        box = new SphereGeometry(3, 60, 60),
        material = new MeshLambertMaterial({
            color: (0x3f7b9d)
        })
    let renderer: WebGLRenderer,
        orbitControls: OrbitControls,
        camera: PerspectiveCamera

    const mesh = new Mesh(box, material),
        scene = new Scene(),
        axesHelper = new AxesHelper(5),
        state = new State(),
        light = new PointLight(),
        ambientLight = new AmbientLight()



    // 光照
    light.position.set(15, 10, 5)
    light.intensity = 120
    // light.power=160
    light.decay = 1
    scene.add(axesHelper, light, ambientLight, mesh)
    function run(t: number) {
        state.update()
        renderer.render(scene, camera);
        requestAnimationFrame(run);
    }
    useEffect(() => {
        const bodyEle = document.body
        camera = new PerspectiveCamera(100, bodyEle.clientWidth / bodyEle.clientHeight, 1, 1000)
        renderer = new WebGLRenderer({
            antialias: true
        })
        renderer.setPixelRatio(window.devicePixelRatio)
        renderer.setClearColor(0x444444, 1)
        orbitControls = new OrbitControls(camera, renderer.domElement)
        document.body.appendChild(state.dom)
        camera.position.set(5, 5, 5)
        camera.lookAt(0, 0, 0)

        const gui = new GUI()
        const fog = new Fog(0x3f7b9d, 0, 60);
        gui.addFolder("材质").add(mesh.position, 'x', 0, 5)
        gui.addFolder("几何体").add(ambientLight, 'intensity', 0, 10)
        // gui配置
        gui.domElement.style.right = '0px';
        gui.domElement.style.width = '300px';
        renderer.setSize(bodyEle.clientWidth * window.devicePixelRatio, bodyEle.clientHeight * window.devicePixelRatio)
        run(0)
        for (const iterator of container.current!.childNodes) {
            iterator.remove()
        }
        container.current!.appendChild(renderer.domElement)

        return () => {
            renderer.dispose()
            gui.destroy()
        }
    }, [])

    return <div ref={container}></div>
}
export default page